<?php
require('common/common.php');

$Input = new Input();
$old_pw = $Input->get('old_pw');
$passwd = $Input->get('passwd');
$return_url = $Input->get('return_url',Input::RAW,null);

User::initialize(db_connect());
$user = User::authenticate_expired($return_url);

if (isset($old_pw)) {
    $old_pw_correct = $user->check_pw($old_pw);
    $new_pw_match = ($passwd === $Input->get('passwd2'));
    if ($old_pw_correct && $passwd && $new_pw_match) {
        $user->set_pw($passwd);
        $user->save();
        $success = true;
    }
}

$form_url = $_SERVER['PHP_SELF'];
if (isset($return_url)) $form_url .= '?return_url='.urlencode($return_url);

?>
<!DOCTYPE html>
<HTML><head>
    <title>New Password</title>
</head>
<body>
    <div id="header"></div><br>
<?php
    if (isset($old_pw)) {
        echo '<div id="msg">';
        if (isset($success)) echo "<h3> Password Successfully Reset!</h3>";
        else if (!$old_pw_correct) echo "<h3>Current Password incorrect.</h3>";
        else if (!$new_pw_match) echo "<h3>New Passwords don't match.</h3>";
        echo '</div>';
    }
?>
    <div id="main"><?php
        if (isset($message)) { 
            echo "<h3>$message</h3>\n";
        }
    ?>
    <h2>New Password:</h2>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF'].'?return_url='.urlencode($return_url); ?>" >
        <label>Current Password: </label><input type="password" name="old_pw" ><br>
        <label>New Password: </label><input type="password" name="passwd" ><br>
        <label>Re-enter Password: </label><input type="password" name="passwd2" ><br>
        <input type="submit">
    </form>
    </div>
</body></HTML>